﻿using System;
using System.Collections.Generic;
using System.Linq;
using UIFramwork;
using UIFramwork.Pool;
using UnityEngine;



namespace RStudio.UIFramwork.Pool
{
    /// <summary>
    /// UI 池中心
    /// </summary>
    public class UnitPoolCenter : MonoSingletonBase<UnitPoolCenter>
    {
        /// <summary>
        /// UI 资产使用库池
        /// </summary>
        public readonly Dictionary<Type, UnitUIPool> Pool;

        public UnitPoolCenter()
        {
            Pool = new Dictionary<Type, UnitUIPool>();
        }



        /// <summary>
        /// 创建池| 基于随机创建资产
        /// </summary>
        /// <returns></returns>
        public static UnitUIPool Create(Type type, GameObject prefab)
        {
            if (prefab == null)
            {
                Debug.LogWarning($"池：{type} 缺失实例游戏对象，请检查！");
                return null;
            }

            bool isContain = Instance.Pool.TryGetValue(type, out UnitUIPool output);
            if (isContain)
            {
                Debug.LogWarning($"池：{type} 已存在于缓存中！忽略创建！");
                return output;
            }


            UnitUIPool unitPool = new GameObject($"{type}").AddComponent<UnitUIPool>();
            {
                unitPool.gameObject.transform.SetParent(Instance.transform);
                unitPool.transform.localScale = Vector3.one;
                unitPool.transform.localRotation = Quaternion.identity;
                unitPool.transform.position = Vector3.zero;

                unitPool.Set(type);
                unitPool.Set(prefab);
            }
            ;

            Instance.Pool.TryAdd(type, unitPool);

            return unitPool;
        }
        /// <summary>
        /// 获取池| 基于路径资产库
        /// </summary>
        /// <remarks>
        /// 如果该资产存在，则返回该资产对应的管理池。
        /// </remarks>
        public static UnitUIPool Get(Type type)
        {
            bool isGet = UnitPoolCenter.Instance.Pool.TryGetValue(type, out UnitUIPool output);
            if (!isGet)
            {
                //Debug.LogError($"池：{type} 未存在于缓存中，请确认是否需要强制创建/手动创建！");
                return null;
            }

            return output;
        }
        /// <summary>
        /// 释放池（指定）
        /// </summary>
        public static void Dispose(Type type)
        {
            if (Instance.Pool.TryGetValue(type, out UnitUIPool output))
            {
                output.Dispose();
            }
        }


        /// <summary>
        /// 释放池（全部）
        /// </summary>
        public void Dispose()
        {
            Instance.Pool.ToList().ForEach(e => e.Value.Dispose());
            Instance.Pool.Clear();
        }


    }
}
